package mao.thinkinjava.concurency.cyclebarrier;

import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author Totoro
 * @date 2020/6/1
 * @explain:
 */
public class CycleBarrierDemo {
    public static void main(String[] args) {
        int nHorse = 10;
        int line = 75;
        ExecutorService exec = Executors.newCachedThreadPool();
        CyclicBarrier barrier = new CyclicBarrier(nHorse,()->{
            StringBuilder builder = new StringBuilder();
            for (int i = 0; i < line; i++) {
                builder.append("=");
            }
            System.out.println(builder.toString());
            for(Horse h : Horse.horses){
                h.summery();
            }
            for(Horse h : Horse.horses){
                if(h.getStride() > line){
                    System.out.println(h+" win");
                    //结束当前所有线程。
                    exec.shutdownNow();
                    return;
                }
            }
        });
        for (int i = 0; i < nHorse; i++) {
            new Horse(barrier);
        }

        for(Horse h : Horse.horses){
            exec.execute(h);
        }
    }
}
